package com.tripspins.app.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.tripspins.app.bo.User;
import com.facebook.model.GraphUser;

/**
 * Created by João.Rutkoski on 10/02/14.
 */
public class UserDAO {

    private SQLiteDatabase database;
    final String UPDATE_LOGIN = "update login set id_user = ?";
    final String UPDATE_LOGOUT = "update login set id_user = null";

    public UserDAO(SQLiteDatabase database) {
        this.database = database;
    }

    public User persist(GraphUser loggedUser) {

        User user = getUser(loggedUser.getId());
        if(user == null)
            user = createUser(loggedUser);

        return user;

    }

    public User persist(User loggedUser) {

        return updateUser(loggedUser);



    }

    private User createUser(GraphUser loggedUser) {

        User user = new User();
        user.setName(loggedUser.getName());
        user.setFacebookId(loggedUser.getId());

        StringBuilder sbInsert = new StringBuilder();
        sbInsert.append("INSERT INTO USERS( TXT_FB_ID ");
        sbInsert.append(                 ", TXT_NAME) " );
        sbInsert.append(         " VALUES ( ? ");
        sbInsert.append(                 ", ?);");


        database.execSQL(sbInsert.toString()
                , new String[] { String.valueOf(loggedUser.getId())
                , loggedUser.getName()});

        user.setId(getLastInsertedRowid());

        TripDAO tripDAO = new TripDAO(database);
        tripDAO.updateUser(user);
        return user;
    }

    private User updateUser(User loggedUser)
    {
        StringBuilder sbUpdate = new StringBuilder();
        sbUpdate.append("update users " );
        sbUpdate.append("set id_on_server  = ? ");
        sbUpdate.append(  ", txt_synced = 'Y' ");
        sbUpdate.append(  ", txt_token = ? ");
        sbUpdate.append("where _id = ?");

        database.execSQL(sbUpdate.toString(),
                new String[]{String.valueOf(loggedUser.getIdOnServer())
                        , loggedUser.getToken()
                        , String.valueOf(loggedUser.getId())
                        });

        return loggedUser;
    }


    private long getLastInsertedRowid() {

        String query = "select last_insert_rowid() ";
        Cursor cursor = database.rawQuery(query, null);
        cursor.moveToFirst();
        long id = cursor.getLong(0);
        cursor.close();
        return id;
    }

    public User getUser(String facebookId)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("Select _id ");
        sb.append(    " , id_on_server ");
        sb.append(    " , txt_fb_id ");
        sb.append(    " , txt_name ");
        sb.append(    " , txt_token ");
        sb.append( " From Users ");
        sb.append(" Where txt_fb_id = ? ");
        Cursor cursorUser = database.rawQuery(sb.toString(), new String[] { String.valueOf(facebookId) });
        User user = cursorToUser(cursorUser);
        cursorUser.close();
        return user;
    }

    private User cursorToUser(Cursor cursorUser) {
        cursorUser.moveToFirst();
        User user = null;
        if (!cursorUser.isAfterLast()) {

            user = new User();
            user.setId(cursorUser.getLong(0));
            user.setIdOnServer(cursorUser.getLong(1));
            user.setFacebookId(cursorUser.getString(2));
            user.setName(cursorUser.getString(3));
            user.setToken(cursorUser.getString(4));
        }
        cursorUser.close();
        return user;
    }

    public User getLoggedUser() {
        StringBuilder sb = new StringBuilder();
        sb.append("Select id_user from Login ");
        Cursor cursorLogin = database.rawQuery(sb.toString(), new String[]{});
        cursorLogin.moveToFirst();
        if(cursorLogin.isAfterLast())return null;
        return getUser(cursorLogin.getLong(0));
    }

    public User getUser(long userId) {
        StringBuilder sb = new StringBuilder();
        sb.append("Select _id ");
        sb.append(    " , id_on_server ");
        sb.append(    " , txt_fb_id ");
        sb.append(    " , txt_name ");
        sb.append(    " , txt_token ");
        sb.append( " From Users ");
        sb.append( " where _id = ? ");

        Cursor cursorUser = database.rawQuery(sb.toString(), new String[]{String.valueOf(userId)});
        cursorUser.moveToFirst();
        if(cursorUser.isAfterLast())
        {
            return null;
        }
        User user = cursorToUser(cursorUser);
        cursorUser.close();
        return user;
    }

    public void persistUserLogin(User loggedLocalUser) {
        database.execSQL(UPDATE_LOGIN,
                new String[]{String.valueOf(loggedLocalUser.getId())});

        TripDAO tripDAO = new TripDAO(database);
        tripDAO.updateUser(loggedLocalUser);

    }
    public void persistUserLogout() {
        database.execSQL(UPDATE_LOGOUT,new String[]{});
    }

}
